let http = require("http");
let fs = require("fs");
let server = http.createServer();

server.listen(8080);
server.on('request', function (req, res) {
    let url = req.url;
    console.log('网页url:' + url);
    //判断静态资源
    if (url.lastIndexOf('.') > -1) {
        console.log('网页url:' + url);
        let path = '.' + url;
        readFileByPromise(path, res);
    } else {
        //判断动态资源，以demo?a=index&c=index为例
        let queryString = url.split("?")[1]; //取'?' 后的数据
        console.log(queryString);   //打印a=index&c=index
        let queryArr = queryString.split('&');  //打印['a=index','c=index'];
        console.log(queryArr);
        let keyVals = [];   //创建一个空数组
        for (let key in queryArr) {  //让key在 queryArr 中遍历
            let vals = queryArr[key];
            // console.log('vals:' +vals); //1.  a=index 2.  c=index
            let temArray = vals.split("=");
            // console.log('temArray:'+temArray);  //1.  a,index   2. c,index
            keyVals[temArray[0]] = temArray[1];  //让a=index c=index
        }   
       
        req.query = keyVals;    //base.js敲完后加(给对象添加一个query)
        let controllerPath = './home/controller/' + keyVals['c'];  //正常的项目.controller 是由多个的，model也是有多个的,所以通过url 可动态的调用
        let controller = require(controllerPath);
        //这时候controllerPath 获取到home/controller/index.js 文件,进行调用
        // console.log(keyVals['a']); //打印index
        //keyVals['a'] 变量,所以在json 里面，要去调用它的key ,用 .方式 key必须是个常量,
        let show = keyVals['a'];
        console.log(controller[show](req,res));  //json 访问,如果key是变量要在[]
    }
})


let promise = function (filename) {

    return new Promise(function (resolve, reject) {

        fs.exists(filename, function (result) {
            if (!result) {
                filename = './home/imgs/404.png';
            }
            fs.readFile(filename, function (err, data) {
                resolve(data);
            })
        })
    })
}

async function readFileByPromise(fileName, res) {
    let data = await promise(fileName);
    if (data) {
        res.write(data);
    }
    res.end();
}
